package com.blb.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 自定义Callable类
 */
public class MyCallable implements Callable<Long> {

    @Override
    public Long call() throws Exception {
        //模拟运算
        long sum = 0;
        for (int i = 0; i < 1000000000; i++) {
            sum += i;
        }
        System.out.println(Thread.currentThread().getName() + "线程执行完毕");
        return sum;
    }

    public static void main(String[] args) {
        //创建FutureTask对象,传入Callable对象
        FutureTask<Long> futureTask = new FutureTask<>(new MyCallable());
        //创建Thread对象
        Thread thread = new Thread(futureTask);
        //启动线程
        thread.start();
        System.out.println(Thread.currentThread().getName() + "线程执行完毕");
        //获得计算结果
        try {
            System.out.println("运算结果是："+futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
